package hcurl

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/gogf/gf/v2/net/gclient"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/util/gconv"
)

var (
	ctx     = gctx.New()
	client  = gclient.New()
	Timeout = 3 // 请求超时时间
)

type Options struct {
	Url             string         // 请求地址
	Params          map[string]any // 参数
	Header          map[string]any // Header 信息
	Auth_Basic_User string         // Auth 校验信息
	Auth_Basic_Pass string         // Auth 校验信息
}

// CURL Get 请求
func (o *Options) CurlGet() string {

	// Header
	if o.Header != nil {
		for k, v := range o.Header {
			s := gconv.Strings(v)
			client.SetHeader(k, s[0])
		}
	}

	r, err := client.
		Timeout(time.Second*time.Duration(Timeout)).
		BasicAuth(o.Auth_Basic_User, o.Auth_Basic_Pass).
		Get(ctx, o.Url, o.Params)

	if err != nil {
		fmt.Println(err)
		errInfo := fmt.Sprintf("CURL Get 请求 失败:%v", err)
		return errInfo
	}
	defer r.Close()

	return r.ReadAllString()
}

// CURL Get 请求
// 获取状态码
func (o *Options) GetStatusCode() int {

	// Header
	if o.Header != nil {
		for k, v := range o.Header {
			s := gconv.Strings(v)
			client.SetHeader(k, s[0])
		}
	}

	r, err := client.
		Timeout(time.Second*time.Duration(Timeout)).
		BasicAuth(o.Auth_Basic_User, o.Auth_Basic_Pass).
		Get(ctx, o.Url, o.Params)

	if err != nil {
		return 0
	}
	defer r.Close()

	return r.StatusCode
}

// CURL Post 请求
func (o *Options) CurlPost() string {

	// Header
	if o.Header != nil {
		for k, v := range o.Header {
			s := gconv.Strings(v)
			client.SetHeader(k, s[0])
		}
	}

	r, err := client.
		Timeout(time.Second*time.Duration(Timeout)).
		BasicAuth(o.Auth_Basic_User, o.Auth_Basic_Pass).
		Post(ctx, o.Url, o.Params)

	if err != nil {
		errInfo := fmt.Sprintf("CURL Post 请求 失败:%v", err)
		return errInfo
	}
	defer r.Close()

	return r.ReadAllString()
}

// CURL PostJson 请求
func (o *Options) CurlPostJson() (res string, err error) {

	// Header
	if o.Header != nil {
		for k, v := range o.Header {
			s := gconv.Strings(v)
			client.SetHeader(k, s[0])
		}
	}

	JsonStr, _ := json.Marshal(&o.Params)

	r, err := client.
		Timeout(time.Second*time.Duration(Timeout)).
		BasicAuth(o.Auth_Basic_User, o.Auth_Basic_Pass).
		Post(ctx, o.Url, string(JsonStr))

	if err != nil {
		return
	}
	defer r.Close()

	res = r.ReadAllString()
	return
}
